<template>
  <div class="add-btn">
    <el-dialog
      title="添加巡查点"
      :visible.sync="dialogVisible"
      width="1200px"
      :append-to-body="true"
      @close="closeDialog"
      :close-on-click-modal="false"
    >
      <div class="range">
        <div class="range-left">
          <div class="range-header">
            <div class="unit">
              <el-input
                placeholder="请输入巡查点名称"
                v-model="search_val"
                size="small"
                clearable
                style="width: 250px; margin-right: 15px"
              >
                <!-- @clear="onClearInput(2)" -->
                <template slot="append">
                  <el-button class="el-icon-search"></el-button>
                </template>
                <!-- @click="onClickInput(2)" -->
              </el-input>
              <el-popover
                placement="bottom"
                width="460"
                trigger="click"
                popper-class="popover"
                size="small"
                v-model="showPopover"
              >
                <div>
                  <el-form
                    label-width="70px"
                    style="margin: 20px 0"
                    class="popover_from"
                  >
                    <el-row
                      v-if="
                        user.roleName === 'TENANT_ADMIN' ||
                        user.roleName === 'ORG_ADMIN'
                      "
                    >
                      <el-col :span="24">
                        <el-form-item size="small" label="组织机构">
                          <TreeSearch
                            style="width: 360px; margin-left: 15px"
                            @changeOrgId="changeOrgId"
                            ref="refTreeSearch"
                          >
                            <!-- @onClear="onClear" -->
                          </TreeSearch>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-form-item size="small" label="联网单位">
                      <el-select
                        size="small"
                        style="width: 360px; margin-left: 15px"
                        clearable
                        v-loadMore="loadMore"
                        @change="changeunitId"
                        v-model="selectedValue"
                        placeholder="请选择联网单位"
                        filterable
                        remote
                        :remote-method="remoteMethod"
                        @clear="handleClear(2)"
                      >
                        <el-option
                          v-for="item in orgList"
                          :label="item.orgName"
                          :value="item.id"
                          :key="item.id"
                        >
                        </el-option>
                        <div
                          class="div_box"
                          v-loading="loading"
                          :style="loading ? '' : 'display: none;'"
                        ></div>
                      </el-select>
                    </el-form-item>
                    <el-row>
                      <el-col :span="24">
                        <el-form-item size="small" label="建筑物">
                          <el-select
                            size="small"
                            style="width: 360px; margin-left: 15px"
                            clearable
                            @change="changeBuildings"
                            @keyup.enter.native="searchList"
                            v-loadMore="loadBuildings"
                            v-model="buildingsName"
                            placeholder="请选择建筑物"
                            filterable
                            remote
                            :remote-method="remoteBuildings"
                            @clear="handleClear(3)"
                          >
                            <el-option
                              v-for="item in buildings"
                              :label="item.name"
                              :value="item.id"
                              :key="item.id"
                            >
                            </el-option>
                            <div
                              class="div_box"
                              v-loading="loading2"
                              :style="loading2 ? '' : 'display: none;'"
                            ></div>
                          </el-select>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="24">
                        <el-form-item size="small" label="楼层">
                          <el-select
                            size="small"
                            style="width: 360px; margin-left: 15px"
                            clearable
                            @change="changeFloors"
                            @keyup.enter.native="searchList"
                            v-loadMore="loadFloors"
                            v-model="floorsName"
                            placeholder="请选择楼层"
                            filterable
                            remote
                            :remote-method="remoteFloors"
                            @clear="handleClear(4)"
                          >
                            <el-option
                              v-for="item in floors"
                              :label="item.name"
                              :value="item.id"
                              :key="item.id"
                            >
                            </el-option>
                            <div
                              class="div_box"
                              v-loading="loading3"
                              :style="loading3 ? '' : 'display: none;'"
                            ></div>
                          </el-select>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="24">
                        <el-form-item size="small" label="安装点">
                          <el-select
                            size="small"
                            style="width: 360px; margin-left: 15px"
                            clearable
                            @change="changeSpaces"
                            v-loadMore="loadSpaces"
                            v-model="spacesName"
                            placeholder="请选择安装点"
                            filterable
                            remote
                            :remote-method="remoteSpaces"
                            @clear="handleClear(5)"
                          >
                            <el-option
                              v-for="item in spaces"
                              :label="item.name"
                              :value="item.id"
                              :key="item.id"
                            >
                            </el-option>
                            <div
                              class="div_box"
                              v-loading="loading4"
                              :style="loading4 ? '' : 'display: none;'"
                            ></div>
                          </el-select>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </el-form>
                  <div class="footer" style="text-align: right">
                    <el-button
                      size="small"
                      @click="resetClick"
                      class="cancel-button"
                      >重 置</el-button
                    >
                    <el-button
                      size="small"
                      @click="searchClick1"
                      class="confirm-button"
                      >确 定</el-button
                    >
                  </div>
                </div>
                <el-button
                  size="small"
                  slot="reference"
                  type="primary"
                  :class="
                    hasSearch ? 'elhasSearch elhasSearch2' : 'elhasSearch2'
                  "
                >
                  高级搜索<i
                    class="el-icon-search"
                    style="margin-left: 5px; font-size: 12px"
                  ></i
                ></el-button>
              </el-popover>
            </div>
          </div>
          <div class="range-bottom">
            <el-table
              :data="pointList"
              class="table"
              :header-cell-style="headerStyle"
              ref="refTable"
              row-key="imei"
              @selection-change="batchSelect"
              height="280px"
            >
              <el-table-column
                align="center"
                type="selection"
                :reserve-selection="true"
                width="60"
              ></el-table-column>
              <el-table-column
                align="center"
                prop="pointName"
                label="巡查点名称"
                min-width="100"
                show-overflow-tooltip
              ></el-table-column>
            </el-table>
          </div>
        </div>

        <div class="range-middle">
          <div class="middle-icon">
            <i class="el-icon-arrow-right"></i>
          </div>
        </div>
        <div class="range-right">
          <div class="range-header"></div>
          <div class="install-table"></div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog" class="cancel-button"
          >取 消</el-button
        >
        <el-button
          size="small"
          @click="submit"
          v-preventReClick="1000"
          class="confirm-button"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import tableStyleMixin from "@mixin/table-style";
import Pagination from "@components/Pagination.vue";
import { mapState } from "vuex";
import advanceSearchMixin from "../mixins/advanceSearch.js";
import TreeSearch from "@components/TreeSearch.vue";
import { reqDeviceList, reqDetectorPage } from "@api/api.js";
export default {
  props: ["orgId", "unitId", "buildingId", "floorId", "spaceId", "treeData"],
  mixins: [tableStyleMixin, advanceSearchMixin],
  components: { Pagination, TreeSearch },
  data() {
    return {
      dialogVisible: false,
      loadingSearch: false,
      search_val: "",
      searchForm: {
        facilityName: "",
        fireOsTypes: [],
        facilityTypes: [],
        status: [],
        orgId: "",
        spaceId: "",
        buildingId: "",
        floorId: "",
        userId: "",
        roleName: "",
        startTime: "",
        endTime: "",
        unitId: "",
      },
      showPopover: false,
      limit: 10,
      page: 1,
      total: 0,
      pointList: [
        {
          id: "67fe140a5c3134594f8f056f",
          storeId: "1101082925990707201",
          orgCode: "001100100",
          pointName: "测试",
          address: "广东省深圳市市辖区",
          tagNumber: "789654123000",
          clockInType: 1,
          patrolItemsList: [
            {
              id: "67fdca0f5c3134594f8f04c3",
              itemsName: "123",
              patrolCategory: [
                {
                  id: "555132648754909184",
                  categoryName: "123",
                  itemsName: null,
                  sort: 1,
                },
              ],
            },
          ],
          patrolItemsNames: "123",
          patrolPerson: [
            {
              userId: 361997,
              name: "系统管理员",
            },
            {
              userId: 385457,
              name: "刘先生",
            },
          ],
          storeName: "默认场所",
        },
        {
          id: "67f8ce35ed9c5303dacea59a",
          companyId: 288711,
          userId: 361997,
          storeId: "1101082925990707201",
          orgCode: "001100100",
          pointName: "消防通道",
          address: "广东省深圳市市辖区",
          tagNumber: "456789123456",
          clockInType: 2,
          patrolItemsList: [
            {
              id: "67f8cdc9ed9c5303dacea599",
              itemsName: "消防通道",
              patrolCategory: [
                {
                  id: "553762261773193216",
                  categoryName: "消防通道是否可正常行走",
                  itemsName: null,
                  sort: 1,
                  remarks: "测试",
                },
              ],
            },
            {
              id: "67fc6a13ed9c5303dacead4d",
              itemsName: "rrqwr2",
              isDefaults: 1,
              patrolCategory: [
                {
                  id: "554754709651591168",
                  categoryName: "wr",
                  itemsName: null,
                  sort: 1,
                },
              ],
            },
            {
              id: "6411387a0f460000c000692d",
              itemsName: "消防泵房",
              patrolCategory: [
                {
                  id: "211",
                  categoryName: "消防泵房配电柜供电是否正常",
                  itemsName: null,
                  sort: 1,
                },
                {
                  id: "212",
                  categoryName: "消防泵房事故应急照明是否正常",
                  sort: 2,
                },
              ],
            },
            {
              id: "6411387a0f460000c0006932",
              itemsName: "发电机房",
              patrolCategory: [
                {
                  id: "191",
                  categoryName: "发电机房自动灭火设施是否处于自动状态",
                  sort: 1,
                },
                {
                  id: "192",
                  categoryName: "发电机房储油间防火措施是否符合要求",
                  itemsName: null,
                  sort: 2,
                },
              ],
            },
            {
              id: "6411387a0f460000c0006928",
              itemsName: "配电房",
              patrolCategory: [
                {
                  id: "171",
                  categoryName: "配电房灭火器材是否正常有效",
                  itemsName: null,
                },
              ],
            },
          ],
          patrolItemsNames: "消防通道,rrqwr2,消防泵房,发电机房,配电房",
          patrolPerson: [
            {
              userId: 361997,
              name: "系统管理员",
            },
            {
              userId: 385457,
              name: "刘先生",
            },
          ],
          storeName: "默认场所",
        },
      ],
      batchDataList: [],
      choseDataDev: [],
      choseData1_copy: [],
      orgList: [],
      loading: false,
    };
  },
  computed: {
    ...mapState(["user"]),
  },
  watch: {
    async dialogVisible(val) {
      if (val) {
        // this.batchDataList = [];
        // this.page = 1;
        // this.limit = 10;
        // await this.getDataList();
        // // 第一次需要赋值翻页的数据
        // this.$nextTick(() => {
        //   this.choseData1_copy.forEach((item, index) => {
        //     let exists = this.deviceList.find(
        //       (item2) => item2.imei === item.imei
        //     );
        //     if (!exists) {
        //       this.$refs.refTable.toggleRowSelection(item, true);
        //     }
        //   });
        // });
      }
    },
  },
  mounted() {},
  methods: {
    // 异步加载树数据
    async loadTreeData() {
      // 模拟API请求
    },

    // 收集节点ID
    collectNodeIds(data, idList = []) {
      if (!data) return idList;

      if (Array.isArray(data)) {
        data.forEach((item) => this.collectNodeIds(item, idList));
        return idList;
      }

      if (data.id) {
        idList.push(data.id);
      }

      if (data.patrolCategory && Array.isArray(data.patrolCategory)) {
        data.patrolCategory.forEach((child) =>
          this.collectNodeIds(child, idList)
        );
      }

      return idList;
    },

    // 递归构建保留结构的树
    buildSelectedTree(nodes, checkedKeys) {
      return nodes
        .map((node) => {
          const newNode = { ...node };
          // 移除checked属性设置
          delete newNode.checked;

          if (newNode.patrolCategory) {
            newNode.patrolCategory = this.buildSelectedTree(
              newNode.patrolCategory,
              checkedKeys
            );
          }

          // 仅判断是否保留节点（不处理选中状态）
          const shouldKeep =
            checkedKeys.includes(newNode.id) ||
            (newNode.patrolCategory && newNode.patrolCategory.length > 0);

          return shouldKeep ? newNode : null;
        })
        .filter(Boolean);
    },

    // 获取设备列表
    async getDataList() {
      // const res = await reqDeviceList(this.page, this.limit, {
      //   userId: this.user.userId,
      //   roleName: this.user.roleName,
      //   tenantId: this.user.tenantId,
      //   buildingId: this.buildingId,
      //   floorId: this.floorId,
      //   spaceId: this.spaceId,
      //   imei: this.search_val || "",
      // });
      // if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      // this.total = res.data.total;
      // this.deviceList = res.data.rows;
      // this.$nextTick(() => {
      //   this.dataReplace();
      // });
    },

    // 数据替换
    dataReplace() {
      // this.choseDataDev.forEach((item) => {
      //   this.deviceList.forEach((dataItem) => {
      //     if (dataItem.imei === item.imei) {
      //       this.$refs.refTable.toggleRowSelection(item, false);
      //       this.$refs.refTable.toggleRowSelection(dataItem, true);
      //     }
      //   });
      // });
    },

    // 搜索
    async searchClick() {
      this.page = 1;
      this.limit = 10;
      this.loadingSearch = true;
      // if (this.activeName == "shebei") {
      //   await this.getDataList();
      // } else {
      //   await this.getDataListTannceqi();
      // }
      this.loadingSearch = false;
    },

    // 点击复选框触发，可跨分页选择
    batchSelect(arr) {
      this.batchDataList = arr;
      this.choseDataDev = arr;
    },

    // 清空
    clearInput() {
      this.page = 1;
      this.limit = 10;
      // this.getDataList();
    },

    closeDialog() {
      // this.choseDataDev = [];
      // this.choseDataTCQ = [];
      // this.$refs.refTable.clearSelection();
      // this.$refs.refTableTanceqi.clearSelection();
      this.dialogVisible = false;
    },
    submit() {
      // this.$emit("getDevices", this.treeData_ed);
      this.closeDialog();
    },
  },
};
</script>
<style lang="less" scoped>
@import url("~@views/style/tablePage.less");
@import url("../../../common.less");
// 范围样式
.range {
  display: flex;
  width: 100%;
  // margin-bottom: 20px;
  justify-content: center;
  .range-left {
    width: 46%;
    height: 420px;
    border: 1px solid @primaryBorderColor;
    .range-bottom {
      height: 340px;
      overflow: auto;
    }
  }

  .range-middle {
    width: 6%;
    display: flex;
    align-items: center;
    justify-content: center;
    .middle-icon {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      background-color: @primaryBgcolor2;
      display: flex;
      align-items: center;
      justify-content: center;
      .el-icon-arrow-right {
        font-size: 20px;
        color: @primaryBorderColor2;
      }
    }
  }

  .range-right {
    width: 46%;
    height: 420px;
    border: 1px solid @primaryBorderColor;
  }
  .range-header {
    height: 60px;
    border-bottom: 1px solid @primaryBorderColor;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    box-sizing: border-box;
    padding: 0 10px;
  }
}
::v-deep .el-tabs--border-card > .el-tabs__header .el-tabs__item.is-active {
  color: #7367f0;
}

::v-deep .el-tabs__header .el-tabs__item.is-active {
  border-bottom: 1px solid #7367f0;
}

/* 修改鼠标移入时的样式 */
::v-deep .el-tabs__item:hover {
  color: #7367f0 !important;
}

::v-deep .el-tabs--border-card {
  border: none !important;
  box-shadow: none !important;
}

::v-deep .el-checkbox__inner {
  background-color: transparent !important;
  border: 1px solid @primaryBorder !important;
}
// 多选框
.el-checkbox {
  color: @primaryThemeTxtColor2 !important;
}

// 单选框
.el-radio__inner {
  background: none !important;
}

::v-deep .el-radio__input.is-disabled .el-radio__inner {
  background: #e1e2e6 !important;
}

::v-deep .el-tree {
  height: calc(100% - 66px);
  background: @primaryHeaderBgcolor;
  border-radius: 0 0 0 6px;
  box-sizing: border-box;
  padding: 12px 10px;
  color: @primaryThemeTxtColor;
}

::v-deep .el-tree-node__content:hover {
  background: @paginationBgcolor !important;
  border-radius: 4px;
}

::v-deep .el-tree-node.is-current > .el-tree-node__content {
  background-color: #7367f0 !important;
  border-radius: 4px;
}

::v-deep .is-current > .el-tree-node__content > .el-tree-node__label {
  color: #f0f0f0;
}
</style>
